import os
import traceback

import paramiko

# 配置 SSH 隧道和连接信息
ssh_host = '192.168.32.156'  # SSH服务器IP
ssh_port = 22  # SSH端口
ssh_user = 'root'  # SSH用户名
ssh_password = 'passwd'  # SSH密码

remote_path = '/etc/init.d/chn.xml'  # 远程文件路径
local_path = 'C:/Users/neiwangji32/ZwAutoTest/Config/上海S3样机(环线)/S3样机配置（3个小车）/chn.xml'  # 本地文件路径

class FileUtils:
    """文件操作工具类"""

    @staticmethod
    def read_file(file_path, remote_host=None, username=None, password=None):
        """读取文件内容，支持本地和远程文件"""
        if remote_host:
            return FileUtils._read_remote_file(file_path, remote_host, username, password)
        else:
            if not os.path.exists(file_path):
                raise FileNotFoundException(f"File not found: {file_path}")
            with open(file_path, 'r', encoding='utf-8') as file:
                return file.read()

    @staticmethod
    def write_file(file_path, content, remote_host=None, username=None, password=None):
        """写入内容到文件，支持本地和远程文件"""
        if remote_host:
            FileUtils._write_remote_file(file_path, content, remote_host, username, password)
        else:
            with open(file_path, 'w', encoding='utf-8') as file:
                file.write(content)

    @staticmethod
    def delete_file(file_path, remote_host=None, username=None, password=None):
        """删除文件，支持本地和远程文件"""
        if remote_host:
            FileUtils._delete_remote_file(file_path, remote_host, username, password)
        else:
            if not os.path.exists(file_path):
                raise FileNotFoundException(f"File not found: {file_path}")
            os.remove(file_path)

    @staticmethod
    def replace_file(local_file_path, remote_file_path, remote_host, username, password):
        """
        替换远程文件内容。
        :param local_file_path: 本地文件路径
        :param remote_file_path: 远程目标文件路径
        :param remote_host: 远程主机地址
        :param username: SSH 用户名
        :param password: SSH 密码
        """
        if not os.path.exists(local_file_path):
            raise Exception(f"Local file not found: {local_file_path}")

        # 使用 SFTP 替换远程文件
        try:
            transport = paramiko.Transport((remote_host, 22))
            transport.connect(username=username, password=password)
            sftp = paramiko.SFTPClient.from_transport(transport)

            # 上传文件替换远程文件
            sftp.put(local_file_path, remote_file_path)
            print(f"File {local_file_path} successfully replaced {remote_file_path} on {remote_host}")
        except Exception as e:
            traceback.print_exc()
        finally:
            if 'sftp' in locals():
                sftp.close()
            if 'transport' in locals():
                transport.close()

    @staticmethod
    def read_remote_file(file_path, remote_host, username, password):
        """读取远程文件内容"""
        try:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(remote_host, username=username, password=password)

            stdin, stdout, stderr = ssh.exec_command(f"cat {file_path}")
            output = stdout.read().decode('utf-8')
            print(output)
            errors = stderr.read().decode('utf-8')

            if errors:
                raise ExecutionException(f"Error reading remote file: {errors.strip()}")
            return output
        finally:
            if 'ssh' in locals():
                ssh.close()


if __name__ == '__main__':
    """
    # print(FileUtils.read_file("C:/Users/neiwangji32/Desktop/my/配置/my/单小车区域/chn.xml"))
    # FileUtils.write_file("C:/Users/neiwangji32/Desktop/my/配置/my/单小车区域/test.txt","123456")
    # FileUtils.delete_file("C:/Users/neiwangji32/Desktop/my/配置/my/单小车区域/test.txt")
    # FileUtils.replace_file(local_path, remote_path, ssh_host, ssh_user, ssh_password)
    # FileUtils.read_remote_file(remote_path, ssh_host, ssh_user, ssh_password)
    """
    FileUtils.replace_file(local_path, remote_path, ssh_host, ssh_user, ssh_password)
